package com.monkeygroup.mygoplus.ecchat.ui.contact;

import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.ecchat.common.utils.ToastUtil;
import com.monkeygroup.mygoplus.ecchat.ui.contact.adapter.MemberListAdapter;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactMemberDTO;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/26.
 */
public class ShakeSearchActivity extends BaseActivity implements View.OnClickListener, SensorEventListener {
    private TextView shake_search_tip;
    private SensorManager mSensorManager;
    private Vibrator vibrator;
    private SoundPool mSoundPool = null;
    private boolean isShaking, isShaked, isLoadingResult = false;
    private HttpModel httpEntity = null;
    private final String TAG = "ShakeSearchActivity";

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_shake_phone);
    }

    @Override
    public void initView() {
        shake_search_tip = (TextView) findViewById(R.id.shake_search_tip);
    }

    @Override
    public void setListener() {

    }

    @Override
    public void doEvent() {
        isShaking = false;
        isShaked = false;

        initSP();
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isShaked = false;
        shake_search_tip.setText(getResources().getString(R.string.contact_shake_tip));
        //获取加速传感器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);

    }

    @Override
    protected void onStop() {
        super.onStop();
        mSensorManager.unregisterListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    /**
     * 獲取搖一搖結果列表
     **/
    private void doShakeResult() {
        isLoadingResult = true;

        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);
        String requestUrl = RequestUrl.baseUrl + RequestUrl.requestShakeList;
        if (httpEntity == null) {
            httpEntity = new HttpModel(requestUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
                @Override
                public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                    httpEntity = null;
                    if (VilidateUtil.isSuccess(resultCode)) {
                        Map<String, Object> map = (Map) data;
                        ContactMemberDTO member = new ContactMemberDTO();
                        if (map.get("username") != null && !map.get("username").equals("")) {
                            member.setName((String) map.get("username"));
                        } else if (map.get("userID") != null && !map.get("userID").equals("")) {
                            member.setName((String) map.get("userID"));
                        } else {
                            member.setName((String) map.get("mobile"));
                        }

                        member.setId((String) map.get("mobile"));
                        member.setHeadUrl((String) map.get("headIcon"));

                        Intent intent = new Intent(ShakeSearchActivity.this, AddFriendSearchResult.class);
                        intent.putExtra("result", member);
                        startActivity(intent);
                    } else {
                        ToastUtil.showMessage(resultMsg);
                    }
                    isLoadingResult = false;
                }
            }, true);

            httpEntity.startRequest();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    private void makeSound() {
        mSoundPool.play(1, 1, 1, 0, 0, 1);

        isShaking = true;
        isShaked = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isShaking = false;
            }
        }, 1000);
    }

    private void initSP() {
        //当前系统的SDK版本大于等于21(Android 5.0)时
        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            //传入音频数量
            builder.setMaxStreams(2);
            //AudioAttributes是一个封装音频各种属性的方法
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            //设置音频流的合适的属性
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            //加载一个AudioAttributes
            builder.setAudioAttributes(attrBuilder.build());
            mSoundPool = builder.build();
        } else {
            //当系统的SDK版本小于21时
            //设置最多可容纳10个音频流，音频的品质为5
            mSoundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        }

        mSoundPool.load(this, R.raw.shakesound, 1);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        int sensortype = event.sensor.getType();
        float[] values = event.values;
        if (sensortype == Sensor.TYPE_ACCELEROMETER) {
            /**
             * X/Y/Z方向任意加速度大于15的时候，表示手機開始震動
             **/
            if (Math.abs(values[0]) > 17 || Math.abs(values[1]) > 17 || Math.abs(values[2]) > 17) {
                vibrator.vibrate(300);
                shake_search_tip.setText(getResources().getString(R.string.contact_shake_tip));
                if (mSoundPool != null && !isShaking) {
                    makeSound();
                }
            } else {
                if (isShaked && !isLoadingResult) {
                    isShaked = false;
                    shake_search_tip.setText(getResources().getString(R.string.contact_shaking));
                    doShakeResult();
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        Log.d("11", "onAccuracyChanged");
    }
}
